//
//  API_async_await_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/12/31.
//

/**
 ## 参考链接
 - [swift中Async-await](https://zhuanlan.zhihu.com/p/669261549)
 - [swift 5.5 新出的 Async 和 Await](https://mp.weixin.qq.com/s?__biz=Mzg3MDk3NzUzNw==&mid=2247484010&idx=1&sn=2a9b3d1efc3f7621caab1a5d352c2723&chksm=ce84db04f9f35212bcdec9e73f94ea1c03ad1ec801338c663f696c3b41e9407b3b1be7ee8542&token=965698642&lang=zh_CN&scene=21#wechat_redirect)
 */

import UIKit

struct User {
    var name: String?
}

struct API1 {
    
    /// 获取用户信息
    /// - Parameter callback: 成功回调，返回 User 对象
    static func fetchUserInfo(callback: @escaping (inout User) -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            var u = User()
            callback(&u)
        }
    }
    
    /// 设置用户信息
    /// - Parameter callback: 成功回调，返回成功或者失败
    static func setUserInfo(callback: @escaping (Bool) -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            callback(true)
        }
    }
}

struct API2 {
    /// 获取用户信息
    /// - Returns: 返回 User 对象
    static func fetchUserInfo() async -> User {
        try? await Task.sleep(for: .seconds(3))
        return User()
    }
    
    /// 设置用户信息
    /// - Returns: 返回成功或者失败
    static func setUserInfo() async -> Bool {
        try? await Task.sleep(for: .seconds(3))
        return true
    }
}

class API_async_await_DemoVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        test1()
        
        Task {
            await test2()
        }
    }
}

extension API_async_await_DemoVC {
    private func test1() {
        API1.fetchUserInfo { user in // 获取用户信息
            user.name = "xxx" // 更改用户信息
            // 更新用户信息
            API1.setUserInfo { isSucceed in
                print(isSucceed ? "用户信息更新成功" : "用户信息更新失败")
            }
        }
    }
    
    private func test2() async {
        // 获取用户信息
        var user = await API2.fetchUserInfo()
        // 更改用户信息
        user.name = "xxx"
        // 更新用户信息
        let isSucceed = await API2.setUserInfo()
        print(isSucceed ? "用户信息更新成功" : "用户信息更新失败")
    }
    
    func fetchImages() async -> UIImage {
        let data = try! Data(contentsOf: URL.init(string: "https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500")!)
        return UIImage(data: data, scale: 1)!
    }
}
